<template>
  <div class="app-container">
    <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="toolbarButtonClickEvent">
      <template #use="{ row }">
        <vxe-switch v-model="row.isValid" size="mini" open-label="有效" close-label="无效" @change="setAvailable(row)">
        </vxe-switch>
      </template>
    </y-table>
    <y-form-dialog :title="formConfig.title" ref="dialogFormRef" :form-options="formConfig"
      @confirm="confirmForm"></y-form-dialog>
    <y-form-dialog :title="powerConfig.title" ref="dialogPowerRef" :form-options="powerConfig"
      @confirm="confirmPowerForm">
      <template #power="{ data }">
        <el-input style="position: sticky;
                            top: 0;
                            left: 0;
                            z-index: 3;
                            background: #fff;" class="mb-1" size="small" placeholder="输入关键字进行过滤" v-model="filterText">
        </el-input>
        <el-tree :data="powerList" ref="tree" show-checkbox node-key="permitTitle" :props="defaultProps"
          default-expand-all :default-checked-keys="defaultCheckedKeys" :filter-node-method="filterNode">
        </el-tree>
      </template>
    </y-form-dialog>
  </div>
</template>

<script>

import {
  getRoleList, updateRole, addRole, setRoleAvailable, getRolePermissionList, getPermissionList, deleteRole
} from '@/api/sys/role' // 接口

import listMixin from '@/mixins/listMixin'

export default {
  mixins: [listMixin],
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  data() {
    return {
      // 权限列表
      filterText: '',
      powerList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permissionList: [],
      // 当前角色下具有的权限
      defaultCheckedKeys: [],
      // 表格配置
      listOptions: {

        // 默认查询数据
        defaultQueryData: {
          // form
          form: {},
          // 分页
          page: {
            pageSize: 50
          },
          // 其他查询参数
          params: {}
        },
        // 获取数据方法
        dataMethod: getRoleList,
        // 表格配置
        tableOptions: {
          height: '',
          rowConfig: {
            keyField: 'tid'
          },
          toolbarConfig: {
            // 按钮组
            buttons: [
              { name: '新增角色', code: 'add', status: 'primary', icon: 'vxe-icon-add' }
            ],
            // 工具栏
            tools: [
              // { type: 'button', code: 'DivCode', icon: 'vxe-icon-edit', circle: true },
            ]
          },
          // 表格列
          columns: [
            { type: 'seq', width: 48, align: 'center' },
            { field: 'roleTitle', title: '角色名称' },
            { field: 'userType', title: '用户类别', dictCode: 'frame_user_type' },
            { field: 'description', title: '角色描述' },
            { field: 'orderNum', title: '排序号' },
            { field: 'isValid', title: '是否有效', slots: { default: 'use' } },
            {
              title: '操作',
              width: 160,
              cellRender: {
                name: 'buttons',
                options: [
                  { content: '修改', name: 'edit' },
                  { content: '授权', name: 'power' },
                  {
                    content: '更多', dropdowns: [
                      { content: '删除', name: 'delete' }
                    ]
                  }
                ],
                events: { click: ({ name, row }) => this.controlSwitch(name, row) }
              }
            }
          ]
        },
        // 查询配置
        formOptions: {
          items: [
            {
              field: 'keywords', title: '角色名称',
              itemRender: { name: 'VxeInput' },
              rules: [{ max: 20, message: '长度不能超过20个字符' }]
            }
          ]
        }
      },
      // 表单配置
      formConfig: {
        title: '角色信息',
        titleWidth: 140,
        items: [
          {
            field: 'roleTitle',
            title: '角色名称',
            required: true,
            itemRender: { name: 'VxeInput', props: { maxlength: 50 } }
          },
          {
            field: 'userType', title: '角色类型', required: true,
            itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'frame_user_type'
              }
            }
          },
          {
            field: 'description',
            title: '角色描述',
            itemRender: { name: 'VxeTextarea', props: { maxlength: 200, placeholder: '多个数据使用英文逗号隔开或换行' } }
          },
          { field: 'orderNum', title: '角色排序', itemRender: { name: 'VxeInput', props: { type: 'number' } } }
        ]
      },
      // 权限配置
      powerConfig: {
        title: '角色权限',
        titleWidth: 140,
        items: [{ titleWidth: 0, span: 24, slots: { default: 'power' } }]
      }
    }
  },
  /**
   * 组件挂载时异步执行的方法
   */
  async mounted() {
    // 动态设置查询参数
    // 此处的目的是根据某些条件或逻辑动态地设置组件的查询参数，以便在加载数据前做好准备
    await this.setFormQuery()

    // 加载数据
    // 通过refs引用调用loadData方法来加载数据
    this.$refs.gridRef.loadData()
  },
  methods: {
    /**
     * 工具栏按钮点击事件处理函数
     * @param {Object} event - 事件对象，包含按钮代码
     * 该函数根据点击的工具栏按钮代码，执行不同的操作
     */
    toolbarButtonClickEvent({ code }) {
      switch (code) {
        case 'add':
          // 执行添加操作，打开表单对话框
          //开启禁用
          this.openFormDialog({ row: {}, refName: 'dialogFormRef' })
          break
        default:
          break
      }
    },
    controlSwitch(name, row) {
      switch (name) {
        case 'edit':
          //开启禁用
          this.openFormDialog({ row, refName: 'dialogFormRef' })
          break
        case 'delete':
          this.deleteRow({ row, deleteMethod: (row) => this.deleteById(row) })
          break
        case 'power':
          this.showUserTypePowerTree(row)
          break
        default:
          break
      }
    },
    // 权限名称过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    //提交表单
    async confirmForm(form) {
      return new Promise((resolve, reject) => {
        this.saveOrUpdate(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    // 保存或修改
    saveOrUpdate(form) {
      if (form.roleId) {
        return updateRole(form)
      } else {
        form.permitTitle = []
        return addRole(form)
      }
    },
    // 修改
    setAvailable(row) {
      setRoleAvailable(row.userId, row.isLocked).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    // 删除
    deleteById(row) {
      deleteRole(row.roleId).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    // 打开树形权限选择框
    showUserTypePowerTree(row) {
      this.openFormDialog({ row, refName: 'dialogPowerRef' })
      this.powerList = []
      getPermissionList(row.userType).then(res => {
        if (res.status) {
          this.permissionList = res.data
          this.permissionListToTree(row.roleId)
        }
      })
    },
    // 权限列表转树形结构
    permissionListToTree(roleId) {
      if (!this.permissionList) {
        return
      }
      this.permissionList.forEach((item, i) => {
        if (!item.parentPermit) {
          item.parentPermit = 'root'
        }
      })
      let obj = this.groupBy(this.permissionList, item => item.parentPermit)
      this.permissionList.forEach((item) => {
        item.children = obj[item.permitTitle] || []
        item.name = item.description
      })
      this.powerList = this.permissionList.filter(item => item.parentPermit === 'root')
      this.getRolePermissionList(roleId)
    },
    // 获取选中行的权限列表
    getRolePermissionList(roleId) {
      this.defaultCheckedKeys = ['']
      getRolePermissionList(roleId).then(res => {
        if (res.status) {
          res.data.forEach(item => {
            this.defaultCheckedKeys.push(item.permitTitle)
          })
          this.$nextTick(() => {
            const nodes = []
            this.defaultCheckedKeys.forEach(item => {
              const node = this.$refs.tree.getNode(item)
              //关键，过滤掉不是叶子节点的
              if (node && node.isLeaf) {
                nodes.push(item)
              }
            })
            this.$refs.tree.setCheckedKeys(nodes, true)
          })
        }
      })
    },
    // 提交权限表单
    confirmPowerForm(form) {
      form.permission = []
      let checkedList = this.$refs.tree.getCheckedNodes()
      checkedList = checkedList.concat(this.$refs.tree.getHalfCheckedNodes())
      if (checkedList) {
        checkedList.forEach(item => {
          form.permission.push(item.permitTitle)
        });
      }
      return this.confirmForm(form);
    },


    groupBy(arr, fn) {
      let obj = {}
      arr.forEach(item => {
        let key = fn(item)
        if (!obj[key]) {
          obj[key] = []
        }
        obj[key].push(item)
      })
      return obj
    },


    async setFormQuery() {
      // this.listOptions.defaultQueryData.form.pageSize = 50
      // this.listOptions.defaultQueryData.form.pageNum = 1
      // this.dictCampusList = await this.getDictItems("campus_list");
      // this.dictCollegeList = await this.getDictItems("college_list");
    },
    getRadioRow() {
      return this.$refs.gridRef.$refs.gridRef.getRadioRecord()
    },
    getCheckboxRow() {
      return this.$refs.gridRef.$refs.gridRef.getCheckboxRecords()
    }
  }
}
</script>

<style lang="scss" scoped></style>
